import urllib
import urllib2
import json
import time
import base64
import hashlib
import hmac
from google.appengine.api import rdbms

conn = rdbms.connect(instance="nicksmapviewer:production", database='nicksmapviewerdb')
cursor = conn.cursor()
cursor.execute("SELECT name, address, lat, lng FROM markers LIMIT 30")
data = cursor.fetchall()

gmeclient = "gme-electranet"
gmeprivatekey = "dtoPEguZZssyA2v8sBQ6Wve1Zjg="

def index():

	return dict(data=data)

def createSignedURL(API_URL, paramaters):
	"""Creates a signed URL to be used with the Google Maps APIs"""
	# Encode the static map paramaters to a format that is usable by the urllib.urlretrieve()
	encodedParameters = urllib.urlencode(paramaters)
	# this is the private maps api key given to Maps API for business customers
	privateKey = gmeprivatekey
	# decode the private key into a binary format that can be used to create the signature
	decodedKey = base64.urlsafe_b64decode(privateKey)
	# this is the url that will be signed by the hmac.new() function
	urlToSign = "%s?%s" % (API_URL,encodedParameters)

	# create the signature this function requires the decoded private key, the url that you wish to
	# create the signature for (this will be comprised of the encoded paramaters as well as the apis URL
	signature = hmac.new(decodedKey, urlToSign, hashlib.sha1)
	# encode the signature so that it is usable by the urllib.urlretrieve() function.
	encodedSignature = base64.urlsafe_b64encode(signature.digest())
	# The final signed URL
	signedUrl = "http://maps.googleapis.com" + API_URL + "?" + encodedParameters + "&signature=" + encodedSignature

	return signedUrl

def googleMapsApi(api, paramaters):

	if api == "geocoder":
		apiURL = "/maps/api/geocode/json"
	elif api == "distance":
		apiURL = "/maps/api/distancematrix/json"
	else:
		return "api not given"

	url = createSignedURL(apiURL, paramaters)
	response = urllib2.urlopen(url)
	rawJsonData = response.read()
	encodedJsonData = json.loads(rawJsonData)

	return encodedJsonData

def getUserAddressData(userInput):

	address = userInput

	encodedJsonData = googleMapsApi("geocoder", {"address": address, "sensor": "false", "client": gmeclient})
	
	addrData = []

	for result in range(0,len(encodedJsonData["results"])):

		info = encodedJsonData["results"][result]["formatted_address"]
		lat = encodedJsonData["results"][result]["geometry"]["location"]["lat"]
		lng = encodedJsonData["results"][result]["geometry"]["location"]["lng"]

		row = (info, lat, lng)
		addrData.append(row)

	return addrData


def getNearestStores():
	storeData = []

	addrData = getUserAddressData(request.vars.userAddressInput)
	origin = addrData[0][0]

	batch = 0
	batchIncrement = 40

	while batch <= len(data):
		destinations = ""

		for row in data[batch:batch+batchIncrement]:
			addressString = row[1]
			destinations += addressString + "|"

		encodedJsonData = googleMapsApi("distance", {"origins": origin, "destinations": destinations, "mode": "driving", "sensor": "false", "client": gmeclient})
		# use this address for testing: 445 S B St, San Mateo, CA
		
		for index, row in enumerate(encodedJsonData["rows"][0]["elements"]):
			if row["status"] == "OK":
				if row["distance"]["value"] < 50000:
					address = encodedJsonData["destination_addresses"][index]
					encodedGeocodeData = googleMapsApi("geocoder", {"address": address, "sensor": "false", "client": gmeclient})
					
					info = encodedGeocodeData["results"][0]["formatted_address"]
					dist = row["distance"]["text"]
					lat = encodedGeocodeData["results"][0]["geometry"]["location"]["lat"]
					lng = encodedGeocodeData["results"][0]["geometry"]["location"]["lng"]

					geocodedData = (info, dist, lat, lng)
					storeData.append(geocodedData)

				else:
					pass
			else:
				pass

		batch += batchIncrement

	if len(storeData) == 0:
		storeData = "null"

	return dict(addrData=addrData, storeData=storeData, data=data)

def getDirections():

	userInput = request.vars.directionsInput
	origin = userInput.split("--")[0]
	destination = userInput.split("--")[1]

	return dict(origin=origin, destination=destination)